<script setup>
import { reactive, ref } from "vue";
import TitleComponent from "@/components/TitleComponent.vue";
import router from "@/router/index.js";
import { deleteAnswerRecords, queryAnswerById, queryAnswerRecordsPage, exportAnswerRecords } from "@/api/answer.js";
import { Message } from "@arco-design/web-vue";
import UserInfoComponent from "@/components/UserInfoComponent.vue";

const pageForm = ref({
  pageSize: 12,
  currentPage: 1,
  appId: '',
  resultName: ''
});
const id = ref(0);
const pageFormRef = ref();
const total = ref(0);

const tableLoading = ref(false);
const tableData = ref([]);

const columns = [
  {
    title: '名称',
    dataIndex: 'resultName',
    ellipsis: true,
    tooltip: true,
    fixed: 'left',
    width: 110
  },
  {
    title: '结果描述',
    dataIndex: 'resultDesc',
    ellipsis: true,
    tooltip: true,
  },
  {
    title: '得分',
    dataIndex: 'resultScore',
    ellipsis: true,
    tooltip: true,
    width: 90,
    sortable: {
      sortDirections: ['ascend', 'descend']
    }
  },
  {
    title: '用户昵称',
    dataIndex: 'nickname',
    ellipsis: true,
    tooltip: true,
    width: 120,
  },
  {
    title: '用户答案（JSON 数组）',
    dataIndex: 'choices',
    ellipsis: true,
    tooltip: true,
  },
  {
    title: '答题时间',
    dataIndex: 'createTime',
    width: 200
  },
  {
    title: '操作',
    dataIndex: 'action',
    slotName: 'optional',
    width: 200,
  }
];

const selectedKeys = ref([]);
const detailVisible = ref(false);
const recordDetail = ref({});

const exportVisible = ref(false);

const rowSelection = reactive({
  type: 'checkbox',
  showCheckedAll: true,
  onlyCurrent: false,
});

// 查询答题记录
const submitPageForm = (flag) => {
  if (flag === 1) {
    pageForm.value.currentPage = 1;
  }
  const params = router.currentRoute.value.params;
  id.value = params.id;
  pageForm.value.appId = id.value;
  tableLoading.value = true;
  queryAnswerRecordsPage(pageForm.value)
    .then(res => {
      if (res.data.code === 1) {
        tableData.value = res.data.data.records;
        total.value = Number(res.data.data.total);
      }
    })
    .catch(error => {
      console.log(error);
    })
    .finally(() => {
      tableLoading.value = false;
    });
};
submitPageForm();

const resetPageForm = () => {
  pageFormRef.value.resetFields();
};

const pageChange = (currentPage) => {
  pageForm.value.currentPage = currentPage;
  submitPageForm();
};

// 删除答题记录
const handleDelete = () => {
  if (selectedKeys.value.length === 0) {
    Message.warning('请先选择要删除的答题记录');
    return;
  }

  deleteAnswerRecords(id.value, selectedKeys.value)
    .then(res => {
      if (res.data.code === 1) {
        Message.success('删除答题记录成功');
        selectedKeys.value = [];
        submitPageForm(1); // 刷新列表
      } else {
        Message.error(res.data.msg || '删除答题记录失败');
      }
    })
    .catch(error => {
      console.error(error);
      Message.error('删除答题记录失败');
    });
};

const handleViewDetail = (id) => {
  queryAnswerById(id)
    .then(res => {
      if (res.data.code === 1) {
        recordDetail.value = res.data.data;
        detailVisible.value = true;
      } else {
        Message.error(res.data.msg || '获取答题记录详情失败');
      }
    })
    .catch(error => {
      console.error(error);
    });
};

const handleExport = () => {
  exportVisible.value = true;
};

// 导出功能处理
const handleInstallTable = () => {
  let data = []
  exportResultToExcel(data)
}

// 导出选中数据功能处理
const handleInstallChooseTable = () => {
  if (selectedKeys.value.length === 0) {
    return Message.warning('未选择数据！')
  }
  let data = [];
  for (let i = 0; i < selectedKeys.value.length; i++) {
    data.push(selectedKeys.value[i])
  }
  exportResultToExcel(data)
}

// 导出表格数据
const exportResultToExcel = (data) => {
  exportAnswerRecords(id.value, data)
    .then(res => {
      if (res.status === 200) {
        const url = window.URL.createObjectURL(new Blob([res.data]));
        const link = document.createElement('a');
        link.href = url;
        link.setAttribute('download', '答题记录表.xlsx');
        document.body.appendChild(link);
        link.click();
        link.remove();

        Message.success('导出成功');
        exportVisible.value = false;
      } else {
        Message.error('导出失败');
      }
    })
    .catch(error => {
      console.log(error);
      Message.error('导出过程中发生错误');
    });
}
</script>

<template>
  <div id="answer-record-page">
    <a-card class="card">
      <title-component title-text="查看答题记录"></title-component>
      <div class="set-container">
        <div class="select-container">
          <a-form :model="pageForm" layout="inline" ref="pageFormRef">
            <a-form-item label="结果名称" field="resultName">
              <a-input v-model="pageForm.resultName" placeholder="请输入结果名称"></a-input>
            </a-form-item>
            <a-form-item>
              <a-button type="primary" class="btn" @click="submitPageForm(1)">查询</a-button>
              <a-button type="outline" class="btn" @click="resetPageForm">重置</a-button>
            </a-form-item>
          </a-form>
        </div>
        <div class="button-container">
          <a-popconfirm
            content="确定要删除选中的答题记录吗？"
            @ok="handleDelete"
            position="br"
          >
            <a-button type="primary" status="danger" class="btn">删除</a-button>
          </a-popconfirm>
          <a-button type="primary" class="btn" @click="handleExport">导出</a-button>
        </div>
      </div>
      <a-divider>答题记录管理</a-divider>
      <div class="table-container">
        <a-table
          stripe
          size="medium"
          :scroll="{ x: 1000 }"
          :loading="tableLoading"
          :pagination="false"
          row-key="id"
          :row-selection="rowSelection"
          v-model:selectedKeys="selectedKeys"
          :columns="columns"
          :data="tableData">
          <template #optional="{ record }">
            <a-button type="text" @click="handleViewDetail(record.id)">详情</a-button>
          </template>
        </a-table>
      </div>
      <a-divider />
      <a-pagination
        size="small"
        :base-size="1"
        :buffer-size="1"
        :total="total"
        :default-page-size="12"
        :current="pageForm.currentPage"
        :page-size="pageForm.pageSize"
        @change="pageChange"
      />
    </a-card>

    <!-- 详情弹窗 -->
    <a-modal
      v-model:visible="detailVisible"
      title="详情"
      :width="300"
      :footer="false"
    >
      <!-- 全部数据描述 -->
      <a-descriptions :column="1" size="mini" title="答题结果">
        <a-descriptions-item label="应用 ID">{{ recordDetail.appId || '未提供' }}</a-descriptions-item>
        <a-descriptions-item label="应用名称">{{ recordDetail.appName || '未提供' }}</a-descriptions-item>
        <a-descriptions-item label="评分类型">
          <a-tag v-if="recordDetail.appType === 1" color="green">测评类</a-tag>
          <a-tag v-else-if="recordDetail.appType === 0" color="red">得分类</a-tag>
        </a-descriptions-item>
        <a-descriptions-item label="评分策略">
          <a-tag v-if="recordDetail.scoringStrategy === 1" color="blue">AI</a-tag>
          <a-tag v-else-if="recordDetail.scoringStrategy === 0" color="orange">自定义</a-tag>
        </a-descriptions-item>
        <a-descriptions-item label="结果名称">{{ recordDetail.resultName || '未提供' }}</a-descriptions-item>
        <a-descriptions-item label="结果描述">{{ recordDetail.resultDesc || '未提供' }}</a-descriptions-item>
        <a-descriptions-item label="答案">{{ recordDetail.choices || '未提供' }}</a-descriptions-item>
        <a-descriptions-item label="得分">{{ recordDetail.resultScore || '未评分' }}</a-descriptions-item>
        <a-descriptions-item label="答题时间">{{ recordDetail.createTime || '未提供' }}</a-descriptions-item>
        <a-descriptions-item label="用户信息">
          <user-info-component :avatar="recordDetail.avatar" :nickname="recordDetail.nickname" :userId="recordDetail.userId" />
        </a-descriptions-item>
        <a-descriptions-item label="结果图片">
          <template v-if="recordDetail.resultPicture">
            <img :src="recordDetail.resultPicture" alt="结果图片" style="max-width: 200px;">
          </template>
          <template v-else>
            无结果图片
          </template>
        </a-descriptions-item>
      </a-descriptions>
    </a-modal>

    <a-modal
      v-model:visible="exportVisible"
      title="导出"
      :width="300"
    >
      将对应数据导出为表格
      <template #footer>
        <a-button @click="exportVisible = false">取消</a-button>
        <a-button type="primary" @click="handleInstallChooseTable">导出选中</a-button>
        <a-button type="primary" @click="handleInstallTable">导出全部</a-button>
      </template>
    </a-modal>
  </div>
</template>

<style scoped>
.card {
  margin-top: 20px;
}

.card {
  margin: 30px 0;
}

.set-container {
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
}

.select-container .btn,
.button-container .btn {
  margin-right: 5px;
}

.detail-image {
  text-align: center;
  margin-bottom: 20px;
}
</style>
